package com.zbkj.admin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zbkj.admin.service.*;
import com.zbkj.common.model.safe.SafeDept;
import com.zbkj.common.model.safe.SafeEnterprise;
import com.zbkj.common.model.safe.SafeRecord;
import com.zbkj.common.model.safe.SafeUser;
import com.zbkj.common.model.sms.SmsRecord;
import com.zbkj.common.model.user.User;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.request.PageParamRequest;
import com.zbkj.common.request.safe.SafeEnterpriseRequest;
import com.zbkj.service.dao.safe.SafeEnterpriseDao;
import com.zbkj.service.dao.safe.SafeUserDao;
import com.zbkj.service.service.SmsRecordService;
import com.zbkj.service.service.SystemConfigService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SafeServiceImpl implements SafeService {


    private OkHttpClient client = null;
    public static final String TIMESTAMP = "https://api-v4.mysubmail.com/service/timestamp";
    private static final String URL = "https://api-v4.mysubmail.com/sms/send";
    public static final String TYPE_MD5 = "md5";
    public static final String TYPE_SHA1 = "sha1";

    @Value("${safe.token}")
    private String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjY2UiOiJjZjUxNzc2NDk3M2YwZWE0MjE3NzM4MGNhNDM2Nzc1ZSIsImV4aW5mbyI6IiIsInBpZCI6IjZjZmJlZGIzNTcyOTUyZDY2ZWYwYTc4ZDlmMjMyNWI3Mjk1OGFmOWY2ZThhMTMzZjdjNGNmNTJlYTI2OTk1NWUiLCJyaWQiOiI3YzAzMDhlYWFmZjU3OTk2ODQzMmY2NTkyOWUwMGM3ZWQ3ZWFkMTFhYzVjZDdiOWM5MmFlNDgwMzJiNjA4NjJlIiwiZXhwIjoxNjY2ODcxMjgyLCJhaWQiOiJlMWI3ZjkwZDYxM2RiMjExMDM2NjkxMzNlMTU1NGIwMzA5ODU1MjE1ZmEzZTg3OWNkNmQxZDFkMmFkN2U1ZDFhIiwiaWF0IjoxNjY2NjEyMDgyLCJkaWQiOiJlMWI3ZjkwZDYxM2RiMjExMDM2NjkxMzNlMTU1NGIwMzA5ODU1MjE1ZmEzZTg3OWNkNmQxZDFkMmFkN2U1ZDFhIn0.vg79avE5Q_MQZu_wzwIJy1086114DHFyZlNPCXuq288";

    @Value("${sms.open}")
    private Boolean smsOpen;

    @Autowired
    private SafeEnterpriseService safeEnterpriseService;

    @Autowired
    private SafeRecordService safeRecordService;

    @Autowired
    private SafeUserService safeUserService;

    @Autowired
    private SmsRecordService smsRecordService;

    @Autowired
    private SafeDeptService safeDeptService;

    @Autowired
    private SystemConfigService configService;

    @PostConstruct
    public void init() {
        client = new OkHttpClient.Builder().connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS).build();
    }

    public List<SafeEnterprise> getEnter(String cityCode) {
        SafeDept safeDept = safeDeptService.getById(safeDeptService.comparePid(cityCode));
        List<SafeEnterprise> safeEnterprises = new ArrayList<>();
        MediaType JSON1 = MediaType.parse("application/json;charset=utf-8");
        JSONObject json = new JSONObject();
        json.put("align", "right");
        json.put("prodAddrCode", cityCode);
        json.put("entFullName", "");
        json.put("entFeature", "");
        json.put("industryparkName", "");
        json.put("industryTypeCode", "");
        json.put("scaleType", "");
        json.put("wssLevel", "");
        json.put("current", 1);
        json.put("maxLength", "6");
        json.put("pages", 0);
        json.put("page", 1);
        json.put("position", "bottom");
        json.put("showQuickJumper", true);
        json.put("showSizeChanger", false);
        json.put("showTotalInfo", true);
        json.put("simple", false);
        json.put("size", 10);
        RequestBody requestBody = RequestBody.create(JSON1, String.valueOf(json));

        Request request = new Request.Builder().url("https://gkaqsc.yjt.zj.gov.cn/jzz-basic/home/gov/shhfw/list")
                .addHeader("Content-Type", "application/json")
                .addHeader("token", safeDept.getToken()).post(requestBody).build();
        int pages = 0;
        int page = 1;
        try {

            Response response = client.newCall(request).execute();
            String string = response.body().string();
            log.info(string);
            JSONObject jsonObject = JSON.parseObject(string);
            if (jsonObject.getInteger("code").equals(1)) {
                JSONObject data = jsonObject.getJSONObject("data");
                int total = data.getInteger("total");
                pages = data.getInteger("pages");
                if (total > 0) {
                    safeEnterprises.addAll(JSONArray.parseArray(data.getJSONArray("records").toJSONString(), SafeEnterprise.class));
                }
                while (page < pages) {
                    page = page + 1;
                    json.put("pages", pages);
                    json.put("page", page);
                    json.put("current", page);
                    requestBody = RequestBody.create(JSON1, String.valueOf(json));
                    request = new Request.Builder().url("https://gkaqsc.yjt.zj.gov.cn/jzz-basic/home/gov/shhfw/list")
                            .addHeader("Content-Type", "application/json")
                            .addHeader("token", safeDept.getToken()).post(requestBody).build();
                    response = client.newCall(request).execute();
                    string = response.body().string();
                    log.info(string);
                    jsonObject = JSON.parseObject(string);
                    if (jsonObject.getInteger("code").equals(1)) {
                        data = jsonObject.getJSONObject("data");
                        total = data.getInteger("total");
                        pages = data.getInteger("pages");
                        if (total > 0) {
                            safeEnterprises.addAll(JSONArray.parseArray(data.getJSONArray("records").toJSONString(), SafeEnterprise.class));
                        }
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return safeEnterprises;

    }

    @Override
    public List<SafeEnterprise> syncEnterpriseList(String cityCode) {
        Map<String, SafeEnterprise> enterpriseMap = new HashMap<>();
        LambdaQueryWrapper<SafeEnterprise> lqw = new LambdaQueryWrapper<>();
        lqw.likeRight(SafeEnterprise::getCityCode, cityCode);
        lqw.eq(SafeEnterprise::getIsDelete, false);
        List<SafeEnterprise> mysqlEnterList = safeEnterpriseService.list(lqw);
        if (CollectionUtil.isNotEmpty(mysqlEnterList)) {
            enterpriseMap = mysqlEnterList.stream().collect(Collectors.toMap(SafeEnterprise::getEntId, ent -> ent));
        }
        List<SafeEnterprise> safeEnterprises = new ArrayList<>();

        safeEnterprises=getEnter(cityCode);
        if(CollectionUtil.isEmpty(safeEnterprises)){
            return mysqlEnterList;
        }
        List<SafeEnterprise> addList = new ArrayList<>();
        for (SafeEnterprise ent : safeEnterprises) {
            if (!enterpriseMap.containsKey(ent.getEntId())) {
                addList.add(ent);
            }
        }
        List<SafeEnterprise> updateList = new ArrayList<>();
        Map<String, SafeEnterprise> newEntMap = safeEnterprises.stream().collect(Collectors.toMap(SafeEnterprise::getEntId, ent -> ent));
        Map<String, SafeEnterprise> newNameEntMap = safeEnterprises.stream().collect(Collectors.toMap(SafeEnterprise::getEntFullName, ent -> ent));
        for (SafeEnterprise ent : mysqlEnterList) {
            if (!newEntMap.containsKey(ent.getEntId())) {
                ent.setIsDelete(true);
                updateList.add(ent);
            }
            if (newEntMap.containsKey(ent.getEntId())) {
                SafeEnterprise safeEnterprise = newEntMap.get(ent.getEntId());
                ent.setPrincipal(safeEnterprise.getPrincipal());
                ent.setPrincipalMphone(safeEnterprise.getPrincipalMphone());
                ent.setEntFullName(safeEnterprise.getEntFullName());
                ent.setCityCode(safeEnterprise.getCityCode());
                ent.setCityName(safeEnterprise.getCityName());
                updateList.add(ent);
            }
        }
        if (CollectionUtil.isNotEmpty(addList)) {
            safeEnterpriseService.saveBatch(addList);
        }
        if (CollectionUtil.isNotEmpty(updateList)) {
            safeEnterpriseService.updateBatchById(updateList);
        }
        return new ArrayList<>();
    }

    @Override
    public CommonPage<SafeEnterprise> entList(SafeEnterpriseRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        LambdaQueryWrapper<SafeEnterprise> lqw = new LambdaQueryWrapper<>();
        if (ObjectUtil.isNotEmpty(request.getCityCode())) {
            lqw.like(SafeEnterprise::getCityCode, request.getCityCode());
        }
        if (ObjectUtil.isNotEmpty(request.getEntFullName())) {
            lqw.like(SafeEnterprise::getEntFullName, request.getEntFullName());
        }
        if (StringUtils.isNotEmpty(request.getSortField())) {
            if (request.isAsc()) {
                lqw.last("order by " + request.getSortField() + " asc");
            }
        }
        List<SafeEnterprise> enterprises = safeEnterpriseService.list(lqw);
        return CommonPage.restPage(enterprises);
    }
    @Override
    public Map<String, Object> dangerSafeRecordOld(Integer days, Integer page,int nearDayStart, int nearDayEnd, String tokenM, String entFullName) {
        List<SafeRecord> safeRecords = new ArrayList<>();
        MediaType JSON1 = MediaType.parse("application/json;charset=utf-8");
        Date beginDate = DateUtil.offsetDay(new Date(), -days);
        JSONObject json = new JSONObject();
        json.put("align", "right");
        json.put("checkDateEnd", DateUtil.format(new Date(), "yyyyMMdd"));
        json.put("checkDateStart", DateUtil.format(beginDate, "yyyyMMdd"));
        json.put("current", page);
        json.put("hdLevel", "");
        json.put("hdSource", "");
        json.put("hdType", "");
        json.put("maxLength", "0");
        json.put("neatenSituation", "X1301");
        json.put("pages", "");
        json.put("position", "bottom");
        json.put("prodAddrCode", "");
        json.put("showQuickJumper", "");
        json.put("showSizeChanger", "");
        json.put("showTotalInfo", "");
        json.put("simple", "");
        json.put("size", 10);
        if (StringUtils.isNotEmpty(entFullName)) {
            json.put("entFullName", entFullName);
        }
        if (nearDayEnd > 0) {
            json.put("neatenLimitDateEnd", DateUtil.format(DateUtil.offsetDay(new Date(), nearDayEnd), "yyyyMMdd"));
            json.put("neatenLimitDateStart", DateUtil.format(DateUtil.offsetDay(new Date(), nearDayStart), "yyyyMMdd"));
        }
        if (nearDayEnd < 0) {
            json.put("neatenLimitDateEnd", DateUtil.format(DateUtil.offsetDay(new Date(), -nearDayEnd), "yyyyMMdd"));
        }
        RequestBody requestBody = RequestBody.create(JSON1, String.valueOf(json));

        Request request = new Request.Builder().url("https://gkaqsc.yjt.zj.gov.cn/xzhjpx-basic-danger/api/hiddendanger/gov/lastedHdData")
                .addHeader("Content-Type", "application/json")
                .addHeader("token", tokenM).post(requestBody).build();
        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            log.info(string);
            JSONObject jsonObject = JSON.parseObject(string);
            return jsonObject.getJSONObject("data");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public Map<String, Object> dangerSafeRecord(Integer days, Integer page,Integer pages
            , int nearDayStart, int nearDayEnd, String tokenM, String entFullName) {
        List<SafeRecord> safeRecords = new ArrayList<>();
        MediaType JSON1 = MediaType.parse("application/json;charset=utf-8");
        Date beginDate = DateUtil.offsetDay(new Date(), -days);
        JSONObject json = new JSONObject();
        json.put("align", "right");
        json.put("checkDateEnd", DateUtil.format(new Date(), "yyyyMMdd"));
        json.put("checkDateStart", DateUtil.format(beginDate, "yyyyMMdd"));
        json.put("current", page);
        json.put("hdLevel", "");
        json.put("hdSource", "X1101");
        json.put("hdType", "");
        json.put("maxLength", "0");
        json.put("neatenSituation", "");
        if(page>0){
            json.put("pages", page);
        }else{
            json.put("pages", "");
        }
        json.put("position", "bottom");
        json.put("prodAddrCode", "");
        json.put("showQuickJumper", false);
        json.put("showSizeChanger", false);
        json.put("showTotalInfo", true);
        json.put("simple", false);
        json.put("size", 10);
        if (StringUtils.isNotEmpty(entFullName)) {
            json.put("entFullName", entFullName);
        }
        if (nearDayEnd > 0) {
            json.put("neatenLimitDateEnd", DateUtil.format(DateUtil.offsetDay(new Date(), nearDayEnd), "yyyyMMdd"));
            json.put("neatenLimitDateStart", DateUtil.format(DateUtil.offsetDay(new Date(), nearDayStart), "yyyyMMdd"));
        }
        if (nearDayEnd < 0) {
            json.put("neatenLimitDateEnd", DateUtil.format(DateUtil.offsetDay(new Date(), -nearDayEnd), "yyyyMMdd"));
        }
        RequestBody requestBody = RequestBody.create(JSON1, String.valueOf(json));

        Request request = new Request.Builder().url("https://gkaqsc.yjt.zj.gov.cn/xzhjpx-basic-danger/api/hiddendanger/gov/lastedHdData")
                .addHeader("Content-Type", "application/json")
                .addHeader("token", tokenM).post(requestBody).build();
        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            log.info(string);
            JSONObject jsonObject = JSON.parseObject(string);
//            return jsonObject.getJSONObject("data");
            return jsonObject;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Map<String, Object> dangerSafeRecordAll(Integer days, Integer page, int nearDayStart
            , int nearDayEnd, String token, String entFullName) {
        List<SafeRecord> safeRecords = new ArrayList<>();
        MediaType JSON1 = MediaType.parse("application/json;charset=utf-8");
        Date beginDate = DateUtil.offsetDay(new Date(), -days);
        JSONObject json = new JSONObject();
        json.put("align", "right");
        json.put("checkDateEnd", DateUtil.format(new Date(), "yyyyMMdd"));
        json.put("checkDateStart", DateUtil.format(beginDate, "yyyyMMdd"));
        json.put("current", page);
        json.put("hdLevel", "");
        json.put("hdSource", "X1101");
        json.put("hdType", "");
        json.put("maxLength", "0");
        json.put("neatenSituation", "");
        json.put("pages", page);
        json.put("position", "bottom");
        json.put("prodAddrCode", "");
        json.put("showQuickJumper", false);
        json.put("showSizeChanger", false);
        json.put("showTotalInfo", true);
        json.put("simple", false);
        json.put("size", 10);
        if (StringUtils.isNotEmpty(entFullName)) {
            json.put("entFullName", entFullName);
        }
        if (nearDayEnd > 0) {
            json.put("neatenLimitDateEnd", DateUtil.format(DateUtil.offsetDay(new Date(), nearDayEnd), "yyyyMMdd"));
            json.put("neatenLimitDateStart", DateUtil.format(DateUtil.offsetDay(new Date(), nearDayStart), "yyyyMMdd"));
        }
        if (nearDayEnd < 0) {
            json.put("neatenLimitDateEnd", DateUtil.format(DateUtil.offsetDay(new Date(), -nearDayEnd), "yyyyMMdd"));
        }
        RequestBody requestBody = RequestBody.create(JSON1, String.valueOf(json));

        Request request = new Request.Builder().url("https://gkaqsc.yjt.zj.gov.cn/xzhjpx-basic-danger/api/hiddendanger/gov/lastedHdData")
                .addHeader("Content-Type", "application/json")
                .addHeader("token", token).post(requestBody).build();
        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            log.info(string);
            JSONObject jsonObject = JSON.parseObject(string);
            JSONObject dataJson=jsonObject.getJSONObject("data");
            if(dataJson.getInteger("current")<dataJson.getIntValue("pages")){

            }
//            return jsonObject.getJSONObject("data");
            return jsonObject;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Map.Entry<String, Integer>> shhfw() {
        Map<String, SafeEnterprise> enterpriseMap = new HashMap<>();
        List<SafeEnterprise> mysqlEnterList = safeEnterpriseService.list();
        if (CollectionUtil.isNotEmpty(mysqlEnterList)) {
            enterpriseMap = mysqlEnterList.stream().collect(Collectors.toMap(SafeEnterprise::getEntFullName, ent -> ent));
        }
        Map<String, Integer> shhfwCountMap = new HashMap<>();

        Request request = new Request.Builder()
                .url("https://gkaqsc.yjt.zj.gov.cn/jzz-basic-zj/zjycs/serviceinfo/list" +
                        "?mediorgFullName=&contractId=&projectName=&entCityCode=330285" +
                        "&enterpriseName=&serviceType=&serviceStartTimeStart=&serviceStartTimeEnd=" +
                        "&position=bottom&align=right&simple=false&current=1&size=1000&pages=0&showTotalInfo=true" +
                        "&showQuickJumper=false&showSizeChanger=true&maxLength=6")
                .addHeader("token", token)
                .addHeader("Content-Type", "application/json")
                .build();
        try {
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            log.info(result);
            JSONObject deptObject = JSON.parseObject(result);
            JSONArray records = deptObject.getJSONObject("data").getJSONArray("records");
            if (CollectionUtil.isNotEmpty(records)) {
                for (int i = 0; i < records.size(); i++) {
                    JSONObject ent = records.getJSONObject(i);
                    String name = ent.getString("enterpriseName");
                    if (shhfwCountMap.containsKey(name)) {
                        shhfwCountMap.put(name, shhfwCountMap.get(name) + 1);
                    } else {
                        shhfwCountMap.put(name, 1);
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 升序比较器
        Comparator<Map.Entry<String, Integer>> valueComparator = new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1,
                               Map.Entry<String, Integer> o2) {
                return o1.getValue() - o2.getValue();
            }
        };
        // map转换成list进行排序
        List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(shhfwCountMap.entrySet());
// 排序
        Collections.sort(list, valueComparator);
        for (int i = 0; i < list.size(); i++) {
            Map.Entry<String, Integer> entry = list.get(i);
            System.out.println(entry.getKey());

        }
        for (int i = 0; i < list.size(); i++) {
            Map.Entry<String, Integer> entry = list.get(i);
            System.out.println(entry.getValue());

        }

        for (int i = 0; i < list.size(); i++) {
            Map.Entry<String, Integer> entry = list.get(i);
            if (enterpriseMap.containsKey(entry.getKey())) {
                System.out.println(enterpriseMap.get(entry.getKey()).getPrincipal() + enterpriseMap.get(entry.getKey()).getPrincipalMphone());
            } else {
                System.out.println();
            }
        }
        for (int i = 0; i < list.size(); i++) {
            Map.Entry<String, Integer> entry = list.get(i);
            if (enterpriseMap.containsKey(entry.getKey())) {
                System.out.println(enterpriseMap.get(entry.getKey()).getCityName());
            } else {
                System.out.println();
            }
        }
        return list;
    }

    @Override
    public void syncSafeUser(String cityCode) {
        SafeDept safeDept = safeDeptService.getById(safeDeptService.comparePid(cityCode));
        List<SafeUser> users = safeUserService.list();
        Map<String, SafeUser> userMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(users)) {
            userMap = users.stream().collect(Collectors.toMap(SafeUser::getPersonId, user -> user));
        }

        Request request = new Request.Builder().url("https://bzhgl.yjt.zj.gov.cn/standard/sys/dept/org/tree?deptId=&sync=1")
                .addHeader("token", safeDept.getToken())
                .addHeader("Content-Type", "application/json")
                .build();
        try {
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            log.info(result);
            JSONObject deptObject = JSON.parseObject(result);
            JSONArray data = deptObject.getJSONArray("data");
            if (CollectionUtil.isEmpty(data)) {
                return;
            }
            JSONObject deptFirst = data.getJSONObject(0);
            syncDeptUser(safeDept.getToken(), deptFirst.getString("id"), userMap, cityCode);
            if (CollectionUtil.isNotEmpty(deptFirst.getJSONArray("children"))) {
                JSONArray children = deptFirst.getJSONArray("children");
                for (int i = 0; i < children.size(); i++) {
                    JSONObject deptChildren = children.getJSONObject(i);
                    syncDeptUser(safeDept.getToken(), deptChildren.getString("id"), userMap, cityCode);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateUser(String personId, Boolean sendSms) {
        LambdaUpdateWrapper<SafeUser> luw = new LambdaUpdateWrapper<>();
        luw.eq(SafeUser::getPersonId, personId);
        luw.set(SafeUser::getSendSms, sendSms);
        safeUserService.update(luw);
    }

    @Override
    public void syncEnterLastOftenCheckDate(String cityCode) {
        SafeDept safeDept = safeDeptService.getById(safeDeptService.comparePid(cityCode));
        Map<String, SafeEnterprise> enterpriseMap = new HashMap<>();
        LambdaQueryWrapper<SafeEnterprise> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SafeEnterprise::getCityCode, cityCode);
        List<SafeEnterprise> mysqlEnterList = safeEnterpriseService.list(lqw);
        if (CollectionUtil.isNotEmpty(mysqlEnterList)) {
            enterpriseMap = mysqlEnterList.stream().collect(Collectors.toMap(SafeEnterprise::getEntId, ent -> ent));
        }
        List<SafeEnterprise> safeEnterprises = new ArrayList<>();
        MediaType JSON1 = MediaType.parse("application/json;charset=utf-8");
        JSONObject json = new JSONObject();
        json.put("align", "right");
        json.put("cityCode", cityCode);
        json.put("entFullName", "");
        json.put("industryEnt", "");
        json.put("industryTypeCode", "");
        json.put("current", 1);
        json.put("maxLength", "6");
        json.put("surveyStatus", "2");
        json.put("pages", 0);
        json.put("position", "bottom");
        json.put("showQuickJumper", false);
        json.put("showSizeChanger", false);
        json.put("showTotalInfo", true);
        json.put("simple", false);
        json.put("size", 2000);
        RequestBody requestBody = RequestBody.create(JSON1, String.valueOf(json));

        Request request = new Request.Builder().url("https://gkaqsc.yjt.zj.gov.cn/jzz-basic/home/gov/cpcx/list")
                .addHeader("Content-Type", "application/json")
                .addHeader("token", safeDept.getToken()).post(requestBody).build();
        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            log.info(string);
            JSONObject jsonObject = JSON.parseObject(string);
            if (jsonObject.getInteger("code").equals(1)) {
                JSONObject data = jsonObject.getJSONObject("data");
                int total = data.getInteger("total");
                JSONArray records = data.getJSONArray("records");
                if (total > 0) {
                    safeEnterprises = JSONArray.parseArray(data.getJSONArray("records").toJSONString(), SafeEnterprise.class);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        for (SafeEnterprise ent : safeEnterprises) {
            if (enterpriseMap.containsKey(ent.getEntId())) {
                enterpriseMap.put(ent.getEntId(), enterpriseMap.get(ent.getEntId()).setLastOftencheckDate(ent.getLastOftencheckDate()));
                enterpriseMap.put(ent.getEntId(), enterpriseMap.get(ent.getEntId()).setSyncTime(new Date()));

            }
        }

        if (CollectionUtil.isNotEmpty(enterpriseMap)) {
            safeEnterpriseService.updateBatchById(enterpriseMap.values());
        }
    }

    @Override
    public void syncEnterSelfCheckDate(String cityCode) {
        SafeDept safeDept = safeDeptService.getById(safeDeptService.comparePid(cityCode));
        String endDayStr = DateUtil.format(new Date(), "yyyyMMdd");
        String beginDayStr = DateUtil.format(DateUtil.offsetDay(new Date(), -360), "yyyyMMdd");

        int pageSize = 100;
        LambdaQueryWrapper<SafeEnterprise> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SafeEnterprise::getCityCode, cityCode);
        List<SafeEnterprise> safeEnterprises = safeEnterpriseService.list(lqw);
        if (CollectionUtil.isEmpty(safeEnterprises)) {
            return;
        }
        ArrayList<SafeRecord> safeRecords = new ArrayList<>(500000);
        for (int i = 0; i < safeEnterprises.size(); i++) {
            SafeEnterprise enterprise = safeEnterprises.get(i);
            int page = 1;
//            JSONObject jsonObject = enterSelfCheckDangeList(cityCode, page, pageSize, beginDayStr
//                    , endDayStr, safeDept.getToken(), enterprise.getEntFullName());
            JSONObject jsonObject =new JSONObject(
                    dangerSafeRecord(120,page,0,0,0,safeDept.getToken(),enterprise.getEntFullName()));
            if (jsonObject.getInteger("code") != 1) {
                continue;
            }
            int resultPage = jsonObject.getJSONObject("data").getInteger("pages");
            safeRecords.addAll(JSONArray.parseArray(jsonObject.getJSONObject("data").getJSONArray("records").toJSONString(), SafeRecord.class));
            while (page < resultPage) {
                page = page + 1;
//                jsonObject = enterSelfCheckDangeList(cityCode, page, pageSize, beginDayStr, endDayStr
//                        , safeDept.getToken(), enterprise.getEntFullName());
                jsonObject =new JSONObject(
                        dangerSafeRecord(120,page,resultPage,0,0
                                ,safeDept.getToken(),enterprise.getEntFullName()));
                if (ObjectUtil.isNotEmpty(jsonObject.getJSONObject("data")) && CollectionUtil.isNotEmpty(jsonObject.getJSONObject("data").getJSONArray("records"))) {
                    if (jsonObject.getInteger("code") != 1) {
                        continue;
                    }
                    safeRecords.addAll(JSONArray.parseArray(jsonObject.getJSONObject("data").getJSONArray("records").toJSONString(), SafeRecord.class));
                }
            }
        }

        Map<String, SafeEnterprise> enterpriseMap = safeEnterprises.stream().collect(Collectors.toMap(SafeEnterprise::getEntId, ent -> ent));
        if (CollectionUtil.isEmpty(safeRecords)) {
            return;
        }
        Map<String, List<SafeRecord>> recordMap = safeRecords.stream().collect(Collectors.groupingBy(SafeRecord::getEntId));
        Date startDateMonth=DateUtil.beginOfMonth(new Date());
        recordMap.forEach((key, value) -> {
            CollectionUtil.sort(value, new Comparator<SafeRecord>() {
                @Override
                public int compare(SafeRecord o1, SafeRecord o2) {
                    Date check1 = DateUtil.parse(o1.getCheckTime());
                    Date check2 = DateUtil.parse(o2.getCheckTime());
                    return check2.compareTo(check1);
                }
            });
            if (enterpriseMap.containsKey(key)) {
                enterpriseMap.get(key).setSelfCheckDate(DateUtil.parseDate(value.get(0).getCheckTime()));
                enterpriseMap.get(key).setSyncTime(new Date());
                int count=0;
                for(SafeRecord safeRecord:value){
                    Date checkDate=DateUtil.parse(safeRecord.getCheckTime(),"yyyy-MM-dd hh:mm:ss");
                    if(checkDate.compareTo(startDateMonth)>0){
                        count++;
                    }
                }
                enterpriseMap.get(key).setSelfCheckCount(count);
            }
        });
        List<SafeEnterprise> updateEntList = new ArrayList<>();
        updateEntList.addAll(enterpriseMap.values());

        safeEnterpriseService.updateBatchById(updateEntList);

    }

    @Override
    public JSONObject enterSelfCheckDangeList(String cityCode
            , int page, int pageSize
            , String beginDateStr, String endDateStr, String deptToken, String entName) {
        Request request = new Request.Builder()
                .url("https://yhpc.yjt.zj.gov.cn:86/xzhjpx-basic-danger/hiddendanger/hiddendangerinfohis/compList?hdSource=X1101" +
                        "&hdLevel=&hdType=&checkTimeStart=" + beginDateStr + "&checkTimeEnd=" + endDateStr + "&entFullName=" + entName + "&neatenSituation=&position=bottom&align=right" +
                        "&simple=false&current=" + page + "&size=" + pageSize + "&pages=0&showTotalInfo=true&showQuickJumper=false&showSizeChanger=false&maxLength=0")
                .addHeader("token", deptToken).get().build();
        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            JSONObject jsonObject = JSON.parseObject(string);
            return jsonObject;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public Map<String, Object> enterCheckDangerList(String hdSource, String checkTimeStart, String checkTimeEnd, String current) {
        return null;
    }

    @Override
    public JSONArray getDept() {
        Request request = new Request.Builder()
                .url("https://bzhgl.yjt.zj.gov.cn/standard/sys/dept/org/tree?deptId=&sync=1")
                .addHeader("token", token).build();
        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            log.info(string);
            JSONObject jsonObject = JSON.parseObject(string);
            return jsonObject.getJSONArray("data");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void sendSafeSms() {
//        int page = 1;
//        List<SafeRecord> safeRecords = new ArrayList<>();
//        JSONObject dangerResult = new JSONObject(dangerSafeRecord(30, page, 0,0));
//        safeRecords.addAll(JSONArray.parseArray(
//                dangerResult.getJSONArray("records").toJSONString(), SafeRecord.class));
//        while (dangerResult.getJSONArray("records").size() == 10) {
//            page++;
//            dangerResult = new JSONObject(dangerSafeRecord(30, page, 0,0));
//            safeRecords.addAll(JSONArray.parseArray(
//                    dangerResult.getJSONArray("records").toJSONString(), SafeRecord.class));
//        }
//        if (CollectionUtil.isEmpty(safeRecords)) {
//            return;
//        }
//        List<SafeEnterprise> enterprises = safeEnterpriseService.list();
//        LambdaQueryWrapper<SafeUser> safeUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        safeUserLambdaQueryWrapper.eq(SafeUser::getSendSms, true);
//        List<SafeUser> safeUsers = safeUserService.list(safeUserLambdaQueryWrapper);
//        Map<String, List<SafeUser>> deptUserMap = safeUsers.stream().collect(Collectors.groupingBy(SafeUser::getDeptFullName));
//        Map<String, SafeEnterprise> enterpriseMap = enterprises
//                .stream().collect(Collectors.toMap(SafeEnterprise::getEntId, ent -> ent));
//        Map<String, List<SafeRecord>> recordMap = new HashMap<>();
//        Map<String, List<SafeRecord>> deptRecordMap = new HashMap<>();
//        safeRecords.forEach(safeRecord -> {
//            if (recordMap.containsKey(safeRecord.getEntId())) {
//                recordMap.get(safeRecord.getEntId()).add(safeRecord);
//            } else {
//                List<SafeRecord> safeRecordList = new ArrayList<>();
//                safeRecordList.add(safeRecord);
//                recordMap.put(safeRecord.getEntId(), safeRecordList);
//            }
//            if (deptRecordMap.containsKey(safeRecord.getProdAddrName())) {
//                deptRecordMap.get(safeRecord.getProdAddrName()).add(safeRecord);
//            } else {
//                List<SafeRecord> safeRecordList = new ArrayList<>();
//                safeRecordList.add(safeRecord);
//                deptRecordMap.put(safeRecord.getProdAddrName(), safeRecordList);
//            }
//        });
//        for (String key : recordMap.keySet()) {
//            SafeEnterprise safeEnterprise = enterpriseMap.get(key);
//            List<SafeRecord> safeRecordList = recordMap.get(key);
//            String content = "【安全在线提醒】" + safeEnterprise.getPrincipal() + " 您好，您的企业"
//                    + safeEnterprise.getEntFullName() + "还有"
//                    + safeRecordList.size() + "条隐患未整改，请及时落实整改，保障安全生产！";
//            System.out.println(content);
//            System.out.println(safeEnterprise.getPrincipal() + safeEnterprise.getPrincipalMphone());
//        }
//
//        for (String key : deptRecordMap.keySet()) {
//            List<SafeRecord> safeRecordList = deptRecordMap.get(key);
//            String deptName = safeRecordList.get(0).getProdAddrName();
//            String deptCode = safeRecordList.get(0).getCheckDeptId();
//            List<SafeUser> users = deptUserMap.get(deptName);
//            if (CollectionUtil.isNotEmpty(users)) {
//                String content = "【安全在线提醒】您所在的" + deptName + "尚有" + safeRecordList.size() + "个隐患未整改！";
//                users.forEach(user -> {
//                    System.out.println(content);
//                    System.out.println(user.getPersonName() + user.getPhone());
//                });
//            }
//        }
    }

    @Override
    public void sendCpcxSms(String cityCode, String type) {
        List<SmsRecord> smsRecords = new ArrayList<>();
        List<SafeEnterprise> safeEnterprises = safeEnterpriseService.list();
        Map<String, SafeEnterprise> enterpriseMap = safeEnterprises.stream().collect(Collectors.toMap(SafeEnterprise::getEntId, ent -> ent));
        List<SafeEnterprise> cpcxEntList = new ArrayList<>();
        int page = 1;
        //临期
        JSONObject result = cpcxEntList(cityCode, "due", page);
        cpcxEntList.addAll(JSONArray.parseArray(result.getJSONArray("records").toJSONString(), SafeEnterprise.class));
        page = page + 1;
        while (result.getInteger("current") <= result.getInteger("pages")) {
            result = cpcxEntList(cityCode, "due", page);
            cpcxEntList.addAll(JSONArray.parseArray(result.getJSONArray("records").toJSONString(), SafeEnterprise.class));
            page = page + 1;
        }
        if (CollectionUtil.isNotEmpty(cpcxEntList)) {
            //发送短信
            cpcxEntList.forEach(ent -> {
                SmsRecord smsRecord = new SmsRecord();
                smsRecord.setType(1);
                smsRecord.setCreateTime(new Date());
                smsRecord.setEntName(ent.getEntFullName());
                smsRecord.setEntId(ent.getEntId());
                if (enterpriseMap.containsKey(ent.getEntId())) {
                    SafeEnterprise safeEnterprise = enterpriseMap.get(ent.getEntId());
                    smsRecord.setPhone(safeEnterprise.getPrincipalMphone());
                    smsRecord.setContent("【安全在线提醒】您的企业距离上次常普常新快90天了，请及时完成常普常新【" + safeEnterprise.getCityName() + "】");
                    smsRecord.setUsername(safeEnterprise.getPrincipal());
                } else {
                    smsRecord.setPhone(ent.getPrincipalMphone());
                    smsRecord.setContent("【安全在线提醒】您的企业距离上次常普常新快90天了，请及时完成常普常新【" + ent.getCityName() + "】");
                    smsRecord.setUsername(ent.getPrincipal());
                }
                smsRecords.add(smsRecord);
            });
        }

        //未完成企业 重点领域
        cpcxEntList.clear();
        page = 1;
        result = cpcxEntList(cityCode, "import", page);
        cpcxEntList.addAll(JSONArray.parseArray(result.getJSONArray("records").toJSONString(), SafeEnterprise.class));
        page = page + 1;
        while (result.getInteger("current") <= result.getInteger("pages")) {
            result = cpcxEntList(cityCode, "import", page);
            cpcxEntList.addAll(JSONArray.parseArray(result.getJSONArray("records").toJSONString(), SafeEnterprise.class));
            page = page + 1;
        }
        if (CollectionUtil.isNotEmpty(cpcxEntList)) {
            //发送短信
            //发送短信
            cpcxEntList.forEach(ent -> {
                SmsRecord smsRecord = new SmsRecord();
                smsRecord.setType(1);
                smsRecord.setCreateTime(new Date());
                smsRecord.setEntName(ent.getEntFullName());
                smsRecord.setEntId(ent.getEntId());
                if (enterpriseMap.containsKey(ent.getEntId())) {
                    SafeEnterprise safeEnterprise = enterpriseMap.get(ent.getEntId());
                    smsRecord.setPhone(safeEnterprise.getPrincipalMphone());
                    smsRecord.setContent("【安全在线提醒】您的企业还未完成常普常新，请及时完成常普常新【" + safeEnterprise.getCityName() + "】");
                    smsRecord.setUsername(safeEnterprise.getPrincipal());
                } else {
                    smsRecord.setPhone(ent.getPrincipalMphone());
                    smsRecord.setContent("【安全在线提醒】您的企业还未完成常普常新，请及时完成常普常新【" + ent.getCityName() + "】");
                    smsRecord.setUsername(ent.getPrincipal());
                }
                smsRecords.add(smsRecord);
            });
        }

        //未完成企业 其他领域
        cpcxEntList.clear();
        page = 1;
        result = cpcxEntList(cityCode, "other", page);
        cpcxEntList.addAll(JSONArray.parseArray(result.getJSONArray("records").toJSONString(), SafeEnterprise.class));
        page = page + 1;
        while (result.getInteger("current") <= result.getInteger("pages")) {
            result = cpcxEntList(cityCode, "other", page);
            cpcxEntList.addAll(JSONArray.parseArray(result.getJSONArray("records").toJSONString(), SafeEnterprise.class));
            page = page + 1;
        }
        if (CollectionUtil.isNotEmpty(cpcxEntList)) {
            //发送短信
            //发送短信
            cpcxEntList.forEach(ent -> {
                SmsRecord smsRecord = new SmsRecord();
                smsRecord.setType(1);
                smsRecord.setCreateTime(new Date());
                smsRecord.setEntName(ent.getEntFullName());
                smsRecord.setEntId(ent.getEntId());
                if (enterpriseMap.containsKey(ent.getEntId())) {
                    SafeEnterprise safeEnterprise = enterpriseMap.get(ent.getEntId());
                    smsRecord.setPhone(safeEnterprise.getPrincipalMphone());
                    smsRecord.setContent("【安全在线提醒】您的企业还未完成常普常新，请及时完成常普常新【" + safeEnterprise.getCityName() + "】");
                    smsRecord.setUsername(safeEnterprise.getPrincipal());
                } else {
                    smsRecord.setPhone(ent.getPrincipalMphone());
                    smsRecord.setContent("【安全在线提醒】您的企业还未完成常普常新，请及时完成常普常新【" + ent.getCityName() + "】");
                    smsRecord.setUsername(ent.getPrincipal());
                }
                smsRecords.add(smsRecord);
            });
        }

        removeTodaySendSmsPhone(smsRecords, 1);
        smsRecordService.saveBatch(smsRecords);
    }

    @Override
    public JSONObject cpcxEntList(String cityCode, String type, int page) {
        Request request = new Request.Builder()
                .url("https://gkaqsc.yjt.zj.gov.cn/jzz-basic/fxbs/cpcx/current-ent-list?entFullName=" +
                        "&cityCode=" + cityCode + "&entFeature=&industryparkName=&industryTypeCode=&type=" + type +
                        "&position=bottom&align=right&simple=false&current=" + page + "&size=100&pages=0&showTotalInfo=true" +
                        "&showQuickJumper=false&showSizeChanger=false&maxLength=6")
                .addHeader("Content-Type", "application/json")
                .addHeader("token", token).get().build();
        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            log.info(string);
            JSONObject jsonObject = JSON.parseObject(string);
            if (jsonObject.getInteger("code").equals(1)) {
                JSONObject data = jsonObject.getJSONObject("data");
                return data;
            } else {
                return new JSONObject();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 自查提醒
     */
    @Override
    public void sendEnterZc(String cityCode, String statMonth, String type) {
        List<SafeEnterprise> safeEnterprises = safeEnterpriseService.list();
        Map<String, SafeEnterprise> enterpriseMap = safeEnterprises.stream().collect(Collectors.toMap(SafeEnterprise::getEntId, ent -> ent));
        Request request = new Request.Builder()
                .url("https://yhpc.yjt.zj.gov.cn:86/xzhjpx-basic-danger/statquery/sstatentselfcheck/no_selfcheck_list" +
                        "?statMonth=" + statMonth + "&cityCode=" + cityCode + "&position=bottom&align=right&simple=false&current=1&size=1000&pages=0&showTotalInfo=true&showQuickJumper=false&showSizeChanger=false&maxLength=6")
                .addHeader("Content-Type", "application/json")
                .addHeader("token", token).get().build();
        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            log.info(string);
            JSONObject jsonObject = JSON.parseObject(string);
            if (jsonObject.getInteger("code").equals(1)) {
                JSONObject data = jsonObject.getJSONObject("data");
                int total = data.getInteger("total");
                JSONArray records = data.getJSONArray("records");
                if (total <= 0) {
                    log.info("未自查企业为空");
                } else {
                    List<SmsRecord> smsRecords = new ArrayList<>();
                    List<SafeEnterprise> safeUNZCEnterprises = new ArrayList<>();
                    safeUNZCEnterprises = JSONArray.parseArray(data.getJSONArray("records").toJSONString(), SafeEnterprise.class);
                    int dayOfMonth = DateUtil.dayOfMonth(new Date());
                    int lastDayOfMonth = DateUtil.dayOfMonth(DateUtil.endOfMonth(new Date()));
                    int span = lastDayOfMonth - dayOfMonth;
                    if (type.equals("manual")) {
                        //每月倒数第7天，向企业发送短信提醒自查
                        safeUNZCEnterprises.forEach(ent -> {
                            SmsRecord smsRecord = new SmsRecord();
                            smsRecord.setType(3);
                            smsRecord.setCreateTime(new Date());
                            smsRecord.setEntName(ent.getEntFullName());
                            smsRecord.setEntId(ent.getEntId());
                            if (enterpriseMap.containsKey(ent.getEntId())) {
                                SafeEnterprise safeEnterprise = enterpriseMap.get(ent.getEntId());
                                smsRecord.setPhone(safeEnterprise.getPrincipalMphone());
                                smsRecord.setContent("【安全在线提醒】您的企业还未完成安全自查，请及时完成自查确保安全生产【" + safeEnterprise.getCityName() + "】");
                                smsRecord.setUsername(safeEnterprise.getPrincipal());
                            } else {
                                smsRecord.setPhone(ent.getPrincipalMphone());
                                smsRecord.setContent("【安全在线提醒】您的企业还未完成安全自查，请及时完成自查确保安全生产【" + ent.getCityName() + "】");
                                smsRecord.setUsername(ent.getPrincipal());
                            }
                            smsRecords.add(smsRecord);
                        });
                    } else {
                        if (span == 7) {
                            //每月倒数第7天，向企业发送短信提醒自查
                            safeUNZCEnterprises.forEach(ent -> {
                                SmsRecord smsRecord = new SmsRecord();
                                smsRecord.setType(3);
                                smsRecord.setCreateTime(new Date());
                                smsRecord.setEntName(ent.getEntFullName());
                                smsRecord.setEntId(ent.getEntId());
                                if (enterpriseMap.containsKey(ent.getEntId())) {
                                    SafeEnterprise safeEnterprise = enterpriseMap.get(ent.getEntId());
                                    smsRecord.setPhone(safeEnterprise.getPrincipalMphone());
                                    smsRecord.setContent("【安全在线提醒】您的企业还未完成安全自查，请及时完成自查确保安全生产【" + safeEnterprise.getCityName() + "】");
                                    smsRecord.setUsername(safeEnterprise.getPrincipal());
                                } else {
                                    smsRecord.setPhone(ent.getPrincipalMphone());
                                    smsRecord.setContent("【安全在线提醒】您的企业还未完成安全自查，请及时完成自查确保安全生产【" + ent.getCityName() + "】");
                                    smsRecord.setUsername(ent.getPrincipal());
                                }
                                smsRecords.add(smsRecord);
                            });
                        }
                        if (span == 3) {
                            //每月倒数3天，向企业和街道管理员发送短信提醒自查
                        }
                    }
                    removeTodaySendSmsPhone(smsRecords, 3);
                    smsRecordService.saveBatch(smsRecords);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void removeTodaySendSmsPhone(List<SmsRecord> smsRecords, Integer smsType) {
        Date begin = DateUtil.beginOfDay(new Date());
        Date end = DateUtil.endOfDay(new Date());
        LambdaQueryWrapper<SmsRecord> lqw = new LambdaQueryWrapper<>();
        lqw.ge(SmsRecord::getCreateTime, begin);
        lqw.le(SmsRecord::getCreateTime, end);
        lqw.eq(SmsRecord::getType, smsType);
        List<SmsRecord> sendedSms = smsRecordService.list(lqw);
        if (CollectionUtil.isEmpty(sendedSms)) {
            return;
        }
        Map<String, List<SmsRecord>> smsRecordMap = sendedSms.stream().collect(Collectors.groupingBy(SmsRecord::getPhone));
        Iterator<SmsRecord> it = smsRecords.iterator();

        while (it.hasNext()) {
            SmsRecord x = it.next();
            if (smsRecordMap.containsKey(x.getPhone())) {
                smsRecordMap.get(x.getPhone()).forEach(smsRecord -> {
                    if (smsRecord.getEntId().equals(x.getEntId())) {
                        it.remove();
                    }
                });
            }

        }

    }

    @Override
    public List<SafeUser> getUserList(String deptId) {
        LambdaQueryWrapper<SafeUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SafeUser::getCityCode, deptId);
        List<SafeUser> userList = safeUserService.list(lqw);
        return userList;
    }

    @Override
    public void updateUser(Boolean sendSms, String personId) {
        LambdaUpdateWrapper<SafeUser> luw = new LambdaUpdateWrapper<>();
        luw.set(SafeUser::getSendSms, sendSms);
        luw.eq(SafeUser::getPersonId, personId);
        safeUserService.update(luw);
        return;
    }

    @Override
    public JSONArray deptTree() {

        Request request = new Request.Builder()
                .url("https://yhpc.yjt.zj.gov.cn:86/xzhjpx-basic-danger/sys/city/tree?sync=1&expand=false&cityId=-1")
                .addHeader("Content-Type", "application/json")
                .addHeader("token", token).get().build();
        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            log.info(string);
            JSONObject jsonObject = JSON.parseObject(string);
            if (jsonObject.getInteger("code").equals(1)) {
                JSONArray data = jsonObject.getJSONArray("data");
                safeDeptService.syncDept(data.getJSONObject(0));
                return data;
            } else {
                return new JSONArray();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public JSONArray sstatentselfcheck(String cityCode, String statMonth) {
        Request request = new Request.Builder()
                .url("https://yhpc.yjt.zj.gov.cn:86/xzhjpx-basic-danger/statquery/sstatentselfcheck/list?cityCode=" + cityCode + "&statMonth=" + statMonth)
                .addHeader("Content-Type", "application/json")
                .addHeader("token", token).get().build();
        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            log.info(string);
            JSONObject jsonObject = JSON.parseObject(string);
            if (jsonObject.getInteger("code").equals(1)) {
                JSONArray data = jsonObject.getJSONArray("data");
                return data;
            } else {
                return new JSONArray();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public JSONObject no_selfcheck_list(String cityCode, String statMonth, int page) {
        Request request = new Request.Builder()
                .url("https://yhpc.yjt.zj.gov.cn:86/xzhjpx-basic-danger/statquery/sstatentselfcheck/no_selfcheck_list" +
                        "?statMonth=" + statMonth + "&cityCode=" + cityCode + "&position=bottom&align=right&simple=false&current=" + page + "&size=10" +
                        "&pages=0&showTotalInfo=true&showQuickJumper=false&showSizeChanger=false&maxLength=6")
                .addHeader("Content-Type", "application/json")
                .addHeader("token", token).get().build();
        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            log.info(string);
            JSONObject jsonObject = JSON.parseObject(string);
            if (jsonObject.getInteger("code").equals(1)) {
                JSONObject data = jsonObject.getJSONObject("data");
                return data;
            } else {
                return new JSONObject();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public JSONArray cpcxStatis() {
        Request request = new Request.Builder()
                .url("https://gkaqsc.yjt.zj.gov.cn/jzz-basic/fxbs/cpcx/current-statis")
                .addHeader("Content-Type", "application/json")
                .addHeader("token", token).get().build();
        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            log.info(string);
            JSONObject jsonObject = JSON.parseObject(string);
            if (jsonObject.getInteger("code").equals(1)) {
                JSONArray data = jsonObject.getJSONArray("data");
                return data;
            } else {
                return new JSONArray();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public CommonPage<SmsRecord> smsList(PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        LambdaQueryWrapper<SmsRecord> lqw = new LambdaQueryWrapper<>();
        if (pageParamRequest.getSended() == 1) {
            lqw.eq(SmsRecord::getSended, false);
        }
        if (pageParamRequest.getSended() == 2) {
            lqw.eq(SmsRecord::getSended, true);
        }
        lqw.orderByDesc(SmsRecord::getId);
        List<SmsRecord> records = smsRecordService.list(lqw);

        return CommonPage.restPage(records);
    }


    private void syncDeptUser(String deptToken, String deptId, Map<String, SafeUser> userMap, String cityCode) {

        FormBody.Builder builder = new FormBody.Builder();
        builder.add("deptId", deptId);
        builder.add("ascnId", deptId);
        FormBody requestBody = builder.build();
        Request request = new Request.Builder().url("https://bzhgl.yjt.zj.gov.cn/standard/sys/person/org/list")
                .addHeader("token", deptToken)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .post(requestBody)
                .build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            String result = response.body().string();
            log.info(result);
            JSONObject resultObject = JSON.parseObject(result).getJSONObject("data");
            JSONArray records = resultObject.getJSONArray("records");
            if (CollectionUtil.isEmpty(records)) {
                return;
            }
            List<SafeUser> safeUsers = JSONArray.parseArray(records.toJSONString(), SafeUser.class);
            List<SafeUser> addUserList = new ArrayList<>();
            for (SafeUser user : safeUsers) {
                if (!userMap.containsKey(user.getPersonId())) {
                    addUserList.add(user);
                }
            }
            if (CollectionUtil.isNotEmpty(addUserList)) {
                safeUserService.saveBatch(addUserList);
            }
        } catch (IOException e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }

    }

    @Override
    public String sendSms(String phone, String content) {
        if (!smsOpen) {
            System.out.println("短信关闭");
            return "短信关闭";
        }
        if (configService.getValueByKey("send_sms").equals("false")) {
            return "数据库短信关闭";
        }
        TreeMap<String, String> requestData = new TreeMap<String, String>();
        String appid = "59882";
        String appkey = "64c58e51ff8de5f717b4a227687bf7e4";
        String sign_type = "md5";
        String sign_version = "2";
//组合请求数据
        requestData.put("appid", appid);
        requestData.put("to", phone);
        if (sign_type.equals(TYPE_MD5) || sign_type.equals(TYPE_SHA1)) {
            String timestamp = getTimestamp();
            requestData.put("timestamp", timestamp);
            requestData.put("sign_type", sign_type);
            requestData.put("sign_version", sign_version);
            String signStr = appid + appkey + RequestEncoder.formatRequest(requestData) + appid + appkey;
            System.out.println(signStr);
            requestData.put("signature", RequestEncoder.encode(sign_type, signStr));
        } else {
            requestData.put("signature", appkey);
        }
        requestData.put("content", content);
        HttpPost httpPost = new HttpPost(URL);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        StringEntity entity = new StringEntity(JSONObject.toJSONString(requestData), "UTF-8");
        httpPost.setEntity(entity);
        try {
            CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
            HttpResponse response = closeableHttpClient.execute(httpPost);
            HttpEntity httpEntity = response.getEntity();
            if (httpEntity != null) {
                String jsonStr = EntityUtils.toString(httpEntity, "UTF-8");
                System.out.println(jsonStr);
                return jsonStr;
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "请求失败";

    }

    @Override
    public String exportSafe(String cityCode, int cpcxEntRemindDay, int cpcxGovDay, int selfCheckEntRemindDay, int selfCheckGovDay, int dangerEntRemindDay, int dangerGovDay) {

        return null;
    }

    public static void main(String[] args) {
//        sendSms("17855847527", "【隐患提醒】测试短信");
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjY2UiOiI0YzI5ODU1YWIxYzM1Y2E4Yjk5YTE5MGIyNDMzY2VjNyIsImV4aW5mbyI6IiIsInBpZCI6ImZlN2U3ZGU2OGI5ZDE5NWQxNmVkMTExYzZjYTA3NTJkM2IyMGQyNDM0MzU4NjU1MjVmMzYzYzBhZjI5ZWIzNTIiLCJyaWQiOiJhMDU2ODI4NWY5NDIxNDc3ZTc3NzU2ZmU0NDdiM2RlNzg0Y2FiZmI1MDZkODBiNjNhOGQ3MThjOGExODBlMmE4IiwiZXhwIjoxNjY4Njk1MTkwLCJhaWQiOiJmYzg2YThhYWJkM2ZlZjNiZjhiODE2M2QwNGRiOTZhYjk0MzU0YmRkYjQ2ODI3NWI2MGVkMDc1Y2MxNzg2M2JhIiwiaWF0IjoxNjY4NDM1OTkwLCJ0aWQiOiIiLCJkaWQiOiJmYzg2YThhYWJkM2ZlZjNiZjhiODE2M2QwNGRiOTZhYjk0MzU0YmRkYjQ2ODI3NWI2MGVkMDc1Y2MxNzg2M2JhIn0.Rl5RhEaejGS1xGHL3sd2bn37M3QMIRFLPPNVK7Qtkv0";
//        SafeServiceImpl safeService=new SafeServiceImpl();
//        JSONObject json=safeService.enterSelfCheckDangeList("330205005",1,10,"20211101","20221110",token);
//        System.out.println(json);
    }

    //获取时间戳
    private static String getTimestamp() {
        CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
        HttpGet httpget = new HttpGet(TIMESTAMP);
        try {
            HttpResponse response = closeableHttpClient.execute(httpget);
            HttpEntity httpEntity = response.getEntity();
            String jsonStr = EntityUtils.toString(httpEntity, "UTF-8");
            if (jsonStr != null) {
                JSONObject json = JSONObject.parseObject(jsonStr);
                return json.getString("timestamp");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
